package com.tristia.resources.impl;

import java.util.LinkedList;
import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.tristia.entity.People;
import com.tristia.entity.Person;
import com.tristia.entity.SuccessInfo;
import com.tristia.resources.PersonResource;
import com.tristia.service.PersonService;

@Component
@Path("/old/people")
@Scope("request")
public class PersonResourceWs implements PersonResource {
	@Autowired
	PersonService personService;
	@Context 
	UriInfo ui;
	private Logger log = Logger.getLogger(this.getClass());
	private List<Person> personList = new LinkedList<Person>();
	private People people = new People();

/*	@GET
	@Produces("application/json")
	public String getPersons() {
		log.info("getPersons entered");

		StringBuffer jsonBuffer = new StringBuffer("{ \"Users\": [");
		List<Person> persons = personService.getAll();
		boolean first = true;
		for (Person person : persons) {
			if (first)
				first = false;
			else
				jsonBuffer.append(",");
			jsonBuffer.append(getJsonPersonObject(person));
		}
		jsonBuffer.append("]}");
		log.info("Sending: \n\n" + jsonBuffer.toString() + "\n\n");
		return jsonBuffer.toString();
	}*/
	
	@GET
	@Path("/list")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML})
	public List<Person> getPersonList() {
		log.info("getPersons entered");
		personList = personService.getAll();
		return personList;
	}
	
	@GET
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public People getPeople() {
		log.info("getPeople entered");
		people.getPeople().addAll(personService.getAll());
		log.info("Sending: \n\n" + people.toString() + "\n\n");
		return people;
	}

/*	@GET
	@Path("/{id}")
	@Produces("application/json")
	public String getPerson(@PathParam("id") String id) {
		log.info("getPerson entered");
		log.info("Hit getPerson");
		Person person = personService.getById(Integer.parseInt(id));
		String result = (String) getJsonPersonObject(person);
		log.info("Sending: \n\n" + result + "\n\n");
		return result;
	}*/
	
	@GET
	@Path("/{id}")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public Person getPerson(@PathParam("id") String id) {
		log.info("getPerson entered");
		log.info("Hit getPerson");
		Person person = personService.getById(Long.parseLong(id));
		log.info("Sending: \n\n" + person.toString() + "\n\n");
		return person;
	}

/*	@PUT
	@Produces("text/plain")
	public String updatePerson(@QueryParam("id") String id,
			@QueryParam("name") String name, @QueryParam("age") String age) {
		log.info("updatePerson entered");
		log.info("name: " + name);
		log.info("age : " + age);
		log.info("id : " + id);

		if (StringUtils.hasText(id)) {
			log.info("It has an ID");
			int idd = Integer.parseInt(id);
			Person person = personService.getById(idd);
			if (person != null) {
				log.info("We found the person with that id");
				person.setAge(Integer.parseInt(age));
				person.setName(name);
				personService.update(person);
			}
		} else {
			Person person = new Person();
			person.setName(name);
			person.setAge(Integer.parseInt(age));
			personService.save(person);
		}
		return "nothing";
	}*/
	
	@PUT
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public SuccessInfo updatePerson(@QueryParam("id") String id,
			@QueryParam("name") String name,
			@QueryParam("age") String age) {
		log.info("updatePerson entered");
		log.info("name: " + name);
		log.info("age : " + age);
		log.info("id : " + id);
		
		SuccessInfo successInfo = new SuccessInfo();
		if (StringUtils.hasText(id)) {
			log.info("It has an ID");
			long idd = Long.parseLong(id);
			Person person = personService.getById(idd);
			if (person != null) {
				log.info("We found the person with that id");
				person.setName(name);
				person.setAge(Integer.parseInt(age));
				personService.update(person);
				successInfo.getSuccesses().add("Updated successfully");
			} else {
				log.info("We do not found the person with that id");
				//errorInfo
			}
		} else {
			log.info("It has not an ID");
			log.info("Put the new person");
			Person person = new Person();
			person.setName(name);
			person.setAge(Integer.parseInt(age));
			personService.save(person);
			successInfo.getSuccesses().add("Created successfully");
		}
		return successInfo;
	}

/*	@POST
	@Produces("text/plain")
	public String addPerson(@QueryParam("name") String name,
			@QueryParam("age") String age) {
		log.info("addPerson entered");
		log.info("name: " + name);
		log.info("age : " + age);

		Person person = new Person();
		person.setName(name);
		person.setAge(Integer.parseInt(age));
		personService.save(person);
		return "nothing";
	}*/
	
	@POST
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public SuccessInfo addPerson(@QueryParam("name") String name,
			@QueryParam("age") String age) {
		log.info("addPerson entered");
		log.info("name: " + name);
		log.info("age : " + age);

		SuccessInfo successInfo = new SuccessInfo();
		Person person = new Person();
		person.setName(name);
		person.setAge(Integer.parseInt(age));
		personService.save(person);
		successInfo.getSuccesses().add("Created successfully");
		return successInfo;
	}

	@DELETE
	@Path("/{id}")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public SuccessInfo deletePerson(@PathParam("id") String id) {
		SuccessInfo successInfo = new SuccessInfo();
		if(id!=null) {
			deletePersonById(id);
		}
		
		MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
		List<String> ids = queryParams.get("id");
		if(ids == null) {
			log.info("\n\nThe ids is null");
		} else {
			for (String currentid : ids) {
				deletePersonById(currentid);
				successInfo.getSuccesses().add("Deleted successfully");
			}
		}
		return successInfo;
	}

	private void deletePersonById(String id) {
		log.info("Delete Id: " + id);
		Person person = personService.getById(Integer.parseInt(id));
		if (person == null) {
			log.info("Null was returned for ID: " + id);
		} else {
			personService.delete(person);
			//successInfo
		}
	}

/*	private Object getJsonPersonObject(Person person) {
		StringBuffer buffer = new StringBuffer("{\"id\": " + person.getId());
		buffer.append(",\"name\": \"").append(person.getName());
		buffer.append("\",\"age\": ").append(person.getAge());
		buffer.append("}");
		return buffer.toString();
	}*/
}
